
<template>
  <div class="clearfix">
    <a-upload
      listType="picture-card"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      :multiple="true"
      :remove="handleRemove"
    >
      <div v-if="fileList.length < 3">
        <a-icon type="plus" />
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        fileList: []
      }
    },
    methods: {
      beforeUpload (file) {
        if (this.fileList.length > 2) {
          return false
        }
        this.exeBase(file)
        return false
      },
      async exeBase (file) {
        await this.getBase64(file, (imageUrl) => {
          if (this.fileList.length < 3 && this.preventRepeat(imageUrl)) {
            const file2 = file
            file2.url = imageUrl
            this.fileList = [...this.fileList, file]
            this.loading = false
          }
        }).then((result) => {
          console.log(result)
        })
      },
      handleRemove (file) {
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
      },
      getBase64 (file, callback) {
        return new Promise((resolve, reject) => {
          let reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = () => {
            callback(reader.result)
            resolve('成功')
          }
        })
      },
      preventRepeat (url) {
        // 排除相同图片
        for (let i = 0, len = this.fileList.length; i < len; i++) {
          if (this.fileList[i].url === url) {
            return false
          }
        }
        return true
      }
    }
  }
</script>